<template>
  <div class="page">
    <div ref="tableHeaderContainer" class="base-search-group-container">
      <form class="base-search" onsubmit="return false;">
        <div class="customer-list-base-search-group">
          <el-input v-model="model.keyWord" :placeholder="$t('common.form.preview.subSparePart.pla2')" v-trim:blur>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-button slot="append" type='primary' @click="model.pageNum=1;search();" native-type="submit" v-track="$track.formatParams('KEYWORD_SEARCH')">{{$t('common.base.search')}}</el-button>
          </el-input>
          <el-button type="plain-third" @click="reset();trackEventHandler('reset')" class="ml_12" v-track="$track.formatParams('RESET_SEARCH')">
            {{$t('common.base.reset')}}
          </el-button>
        </div>
        <span class="advanced-search-visible-btn" @click.stop="isExpand = !isExpand;trackEventHandler('advSearch')" >
          <i class="iconfont icon-filter"></i>
          {{$t('common.base.advancedSearch')}}
        </span>
      </form>
    </div>

    <base-search-drawer
      :show='isExpand'
      @close='closeDrawer'
      @reset='reset'
      @search='search'
      :show-setting='false'
    >
      <el-form label-position="top" :model='model'>
        <!--备件名称-->
        <el-form-item :label="$t('common.form.preview.sparepart.colum1')">
          <el-input :placeholder="$t('part.list.text6')" v-model="model.name" maxlength="1000"></el-input>
        </el-form-item>
        <el-form-item :label="$t('part.partType')">
          <el-select :placeholder="$t('part.list.text7')" v-model="model.type">
            <el-option :label="$t('common.base.all')" value=""></el-option>
            <el-option :label="item" :value="item" v-for="item in types" :key="item"></el-option>
          </el-select>
        </el-form-item>
        <!--备件规格-->
        <el-form-item :label="$t('common.form.preview.sparepart.label3')">
          <el-input :placeholder="$t('part.list.text8')" v-model="model.standard" maxlength="1000"></el-input>
        </el-form-item>
        <!--说明-->
        <el-form-item :label="$t('common.base.explain')">
          <el-input :placeholder="$t('part.list.text9')" v-model="model.description" maxlength="1000"></el-input>
        </el-form-item>
        <el-form-item :label="$t('part.list.text10')">
          <el-select :placeholder="$t('part.list.text7')" v-model="model.enable">
            <el-option :label="$t('common.base.all')" value=""></el-option>
            <el-option :label="$t('common.base.enableState.0')" value="1"></el-option>
            <el-option :label="$t('common.base.enableState.1')" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.base.column.createTime')">
          <el-date-picker style="width:100%;"
                             :value="dateRange"
                             @input="chooseDate"
                             type="daterange"
                             align="right"
                             unlink-panels
                             value-format="timestamp"
                             :default-time="['00:00:00', '23:59:59']"
                             range-separator="-"
                             :start-placeholder="$t('common.base.startDate')"
                             :end-placeholder="$t('common.base.endDate')">
          </el-date-picker>
        </el-form-item>
        <!--关联产品类型：超级二维码开启并且持有备件和使用记录有-->
        <template v-if="openSuperCodePro">
          <el-form-item :label="$t('common.form.type.related_catalog')">
            <el-select :placeholder="$t('part.list.text11')" v-model="model.productTypeList" multiple filterable>
              <el-option :label="item.catalogName" :value="item.id" v-for="item in productType" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-form>
    </base-search-drawer>

    <div ref="tableDoContainer" class="base-operation-bar-container" style="border: none">
      <div class="top-btn-group task-flex task-ai">
        <el-button type="primary" @click="create" v-if="allowCreate" v-track="$track.formatParams('TO_CREATE')">
          <i class="iconfont icon-add task-font14"></i>
          {{$t('common.base.create')}}
        </el-button>
        <el-button type="plain-third" v-if="allowEdit" @click="openEditSparepartDialog" v-track="$track.formatParams('BATCH_EDIT')">
          <i class="iconfont icon-edit-square task-font14"></i>
          {{$t('common.base.bulkEdit')}}
        </el-button>
        <el-button type="plain-third" v-if="allowDelete" @click="remove" v-track="$track.formatParams('DELETE')">
          <i class="iconfont icon-delete task-font14"></i>
          {{$t('common.base.delete')}}
        </el-button>
      </div>
      <div class="action-button-group">

        <el-dropdown trigger="click" :show-timeout="150" v-if="allowImportAndExport" @command="trackEventHandler('moreAction')">
          <span class="el-dropdown-link cur-point">
            {{$t('common.base.moreOperator')}}
            <i class="iconfont icon-more"></i>
          </span>

          <el-dropdown-menu slot="dropdown" class="dropdown-more">
            
            <el-dropdown-item v-if="!isExperienceEdition && isButtonDisplayed && allowImport">
              <span class="dropdown-item" @click="importPart" v-track="$track.formatParams('IMPORT_PART', null, 'MORE_ACTIONS')">{{$t('part.list.text1')}}</span>
            </el-dropdown-item>
            
            <el-dropdown-item v-if="isButtonDisplayed && allowExport">
              <span class="dropdown-item" @click="exportPart(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{$t('common.base.export')}}</span>
            </el-dropdown-item>
            
            <el-dropdown-item v-if="isButtonDisplayed && allowExport">
              <span class="dropdown-item" @click="exportPart(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{$t('common.base.exportAll')}}</span>
            </el-dropdown-item>

            <el-dropdown-item v-if="!isExperienceEdition && allowImport && allowInout">
              <span class="dropdown-item" @click="importEditPart" v-track="$track.formatParams('BATCH_UPDATE', null, 'MORE_ACTIONS')">{{$t('common.base.batchUpdate')}}</span>
            </el-dropdown-item>

          </el-dropdown-menu>
        </el-dropdown>

        <el-dropdown :hide-on-click="false" trigger="click" :show-timeout="150" v-track="$track.formatParams('SELECT_COLUMN')">
          <span class="el-dropdown-link cur-point">
            {{$t('common.base.choiceCol')}}
            <i class="iconfont icon-more"></i>
          </span>

          <el-dropdown-menu slot="dropdown" class="dropdown-more">
            <el-dropdown-item v-for="column in columns" :key="column.field">
              <el-checkbox :value="column.show" @input="chooseColnum(column)" class="dropdown-item">{{column.label}}</el-checkbox>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

      </div>
    </div>

    <!-- <div ref="BaseSelectionBarComponent" class="base-selection-wrapper">
      <base-selection-bar ref="baseSelectionBar" v-model="selected" @toggle-selection="toggleSelection" @show-panel="() => multipleSelectionPanelShow = true" />
    </div> -->

    <div class="table-container">
      <el-table ref="table"
                v-table-style
                v-loading="pageLoading"
                border
                stripe
                :data="page.list"
                :height="tableContainerHeight"
                class="bbx-normal-list-box"
                @select="handleSelection"
                @select-all="handleSelection"
                @header-dragend="headerDragend"
                header-row-class-name="base-table-header-v3"
                @sort-change="sort">
                  <template slot="empty">
                    <BaseListForNoData v-show="!pageLoading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
                  </template>
        <el-table-column
          type="selection"
          align='center'
          fixed
          width="44">
        </el-table-column>

        <el-table-column v-for="column in showColnums" :key="column.field"
                            :label="column.label"
                            :min-width="column.minWidth"
                            :width="column.width"
                            :prop="column.field"
                            :sortable="column.sortable"
                            :fixed="column.fixed"
                            :class-name="column.field == 'serialNumber' ? 'part-name-superscript-td' : ''"
                            :show-overflow-tooltip="column.showTip !== false && column.field !== 'serialNumber'">

          <template slot-scope="scope">

            <template v-if="column.field == 'serialNumber'">
              <a
                class="table-whitelist table-primary"
                :href="`${$resourcePrefix}/partV2/category/detail?id=${scope.row.id}`"
                @click.prevent="openDetail(scope.row)">
                {{scope.row.serialNumber}}
              </a>  
            </template>

            <template v-else-if="column.field == 'enable'">
              <el-switch
                v-if="allowEdit"
                v-model="scope.row.enable"
                :key="scope.row.id"
                :disabled="scope.row.disabled"
                :active-value="1" :inactive-value="0"
                @change="toggleEnable(scope.row)"></el-switch>
              <span> {{scope.row.enable == 1 ? $t('common.base.enableState.0') : $t('common.base.enableState.1')}}</span>
            </template>
            
            <!--关联产品类型-->
            <template v-else-if="column.field == 'productTypeList'">
              <div v-if="scope.row.productTypeList && scope.row.productTypeList.length!=0">
                <label
                  style="color: #55B7B4;cursor: pointer"
                  v-for="(item, index) in scope.row.productTypeList"
                  :key="`${index}_${scope.row.id}`" 
                  @click="openProductMenuTab(item.id)">
                  {{ item.catalogName }}<span v-if="index!=scope.row.productTypeList.length-1">,</span>
                </label>
              </div>
            </template>
            <!--关联产品类型-->
            <template v-else-if="column.field == 'createTime'">
              {{ scope.row[column.field] | formatDate }}
            </template>
            <template v-else>
              {{scope.row[column.field]}}
            </template>
          </template>

        </el-table-column>
      </el-table>
    </div>


    <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer pad-b-16 bg-w pad-t-16">
      <div class="list-info">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{ page.total }}</span>
        </i18n>
        <template v-if="selected&&selected.length>0">
          <i18n path="common.base.table.selectedNth">
            <span place="count" class="base-table-selected-count" @click="multipleSelectionPanelShow = true">{{ selected.length }}</span>
          </i18n>
          <span class="base-table-selected-count" @click="toggleSelection()">{{$t('common.base.clear')}}</span>
        </template>
      </div>
      <el-pagination
        class="customer-table-pagination"
        background
        @current-change="jump"
        @size-change="pageSizeChange"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="model.pageSize"
        :current-page="model.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="page.total">
      </el-pagination>
    </div>


    <base-import ref="importPart"
                 v-if="allowImportAndExport"
                 :template-url="partCategoryListImportTem" 
                 :action="categoryListViewSparePartImport"></base-import>

    <base-export1 ref="exportPanel" 
                 v-if="allowImportAndExport"
                 :columns="exportColumns"
                 :action="partCateGoryListExport"
                 :method="'post'"></base-export1>

    <part-import ref="importEditPart" 
                 v-if="allowEdit" :title="$t('common.base.sparePart')" :selected="selected" :total="page.total"
                 :name="$t('part.list.text12')"
                 :template-url="categoryListViewImportTem" 
                 :template-blank-url="categoryListViewImportTem_2"
                 :template-params="editPartPostParam"
                 :action="categoryListViewImport" @success="importSucc">
      <el-popover slot="explain" trigger="hover">
        <ul class="title-explain">
          <li>{{$t('part.list.text3')}}</li>
          <li>{{$t('part.list.text4')}}</li>
        </ul>
        <stats-popover-icon slot="reference"></stats-popover-icon>
      </el-popover>
    </part-import>

    <el-dialog :title="$t('common.base.bulkEdit')" :visible.sync="editBatchDialog" width="420px">
      <part-edit-batch-form :fields="fields" :types="types" :units="units" ref="editBatchForm" ></part-edit-batch-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="plain-third" @click="editBatchDialog = false" >{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="editBatch" :disabled="pending">{{$t('common.base.makeSure')}}</el-button>
        <!--<el-button @click="editBatchDialog = false">取 消</el-button>-->
        <!--<el-button type="primary" @click="editBatch" :disabled="pending">确 定</el-button>-->
      </div>
    </el-dialog>


    <base-panel :show.sync="multipleSelectionPanelShow" width="420px">
      <h3 slot="title" style="display: flex;justify-content: space-between;align-items: center">
        <span>{{$t('part.list.text5', {data1: selected.length})}}</span>
        <span v-if="selected.length" class="part-panel-btn" @click="toggleSelection()" :title="$t('common.base.tip.clearChoseDataTip')" data-placement="right" v-tooltip></span>
      </h3>

      <div class="part-selected-panel">
        <div class="part-selected-tip" v-if="!selected.length">
          <img :src="noDataImage">
          <p>{{$t('common.base.tip.noSelectedDataFromList')}}</p>
        </div>
        <template v-else>
          <div class="part-selected-list">
            <div class="part-selected-row part-selected-head">
              <span class="part-selected-sn">{{$t('common.base.serialNumber')}}</span>
              <span class="part-selected-name">{{$t('common.base.sparePart')}}</span>
            </div>
            <div class="part-selected-row" v-for="c in selected" :key="c.id">
              <span class="part-selected-sn">{{c.serialNumber}}</span>
              <span class="part-selected-name">{{c.name}}</span>
              <el-button type="button" class="part-selected-delete" @click="cancelSelectPart(c)">
                <i class="iconfont icon-fe-close"></i>
              </el-button>
            </div>
          </div>
        </template>
      </div>
    </base-panel>

  </div>
</template>

<script>
// pageDes 备件品类列表
import _ from 'lodash';
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
import { safeNewDate } from '@src/util/time';

import Page from '@src/model/Page';
import AuthUtil from '@src/util/auth';
import StorageUtil from '@src/util/storageUtil';
import PartEditBatchForm from './form/PartEditBatchForm.vue';
import PartImport from './components/PartImport.vue';

import BaseSearchDrawer from 'packages/BaseSearchDrawer/BaseSearchDrawer.vue';
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import VersionMixin from '@src/mixins/versionMixin/index.ts'
/* export & import */
import { partCateGoryListExport } from '@src/api/Export';
/* export & import */
import { partCategoryListImportTem, categoryListViewImport, categoryListViewImportTem, categoryListViewImportTem_2, categoryListViewSparePartImport } from '@src/api/Import';

import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform';

import TableForStashWidth from '@src/mixins/tableForStashWidth/index.js'
import { formatDate, objectDateToTimestamp } from 'pub-bbx-utils';
import { defaultTableData } from '@src/util/table'

/* constants */
const STORAGE_COLNUM_KEY = 'category_list_column';
const STORAGE_PAGESIZE_KEY = 'category_list_pagesize';
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
export default {
  name: 'part-list-view',
  inject: ['initData'],
  mixins: [VersionMixin, ThemeMixin, TableForStashWidth],
  data(){
    let pageSize = StorageUtil.get(STORAGE_PAGESIZE_KEY) || 10;
    let originModel = {
      name: '', // 备件名称
      description: '', // 说明
      standard: '', // 规格
      productTypeList: [], // 关联产品类型
      keyWord: '',
      type: '',
      enable: '',
      timeStart: '',
      timeEnd: '',
      pageNum: 1,
      pageSize,
      sortBy: {}
    };

    return {
      defaultTableData,
      noDataImage,
      isButtonDisplayed: checkButtonDisplayed(),
      selectColumnState: 'partV2_catalogList',
      drawerSize:'40%',
      selectedLimit: 500,
      auths: {},
      columns: [],
      exportColumns:[],
      isExpand: false,
      pending: false,
      editBatchDialog: false,
      
      types: [],
      units: [],
      productType: [],
      originModel,
      model: _.assign({}, originModel),

      page: new Page(),
      selected: [],
      dateRange: [],

      editPartParam:'',
      editPartPostParam: {},

      maxHeight: window.innerHeight - 180,
      multipleSelectionPanelShow: false,
      fields: [{
        name: this.$t('common.base.name'),
        field: 'name'
      }, {
        name: this.$t('common.form.preview.serviceItem.colum3'),
        field: 'type'
      }, {
        name: this.$t('common.form.preview.sparepart.label3'),
        field: 'standard'
      }, {
        name: this.$t('common.form.preview.serviceItem.colum4'),
        field: 'unit'
      }, {
        name: this.$t('product.component.miniTable.partType.salePrice'),
        field: 'salePrice'
      }, {
        name: this.$t('product.component.miniTable.partType.costPrice'),
        field: 'costPrice'
      }],
      openSuperCodePro: true, // 是否开启超级二维码
      partCateGoryListExport,
      partCategoryListImportTem,
      categoryListViewImport,
      categoryListViewImportTem,
      categoryListViewImportTem_2,
      categoryListViewSparePartImport,
      pageLoading:true,
      tableContainerHeight:'440px',
    }
  },
  props: {
    initData: {
      type: Object,
      default: () => ({})
    }
  },
  filters: {
    formatDate (val) {
      if (!val) return '';
      return formatDate(val);
    },
  },
  computed: {
    
    // 筛选可显示
    showColnums(){
      return this.columns.filter(item => item.show);
    },
    // 是否允许编辑、删除备件
    allowEdit(){
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_EDIT');
    },
    allowDelete(){
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_DELETE');
    },
    allowCreate() {
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_CREATE');
    },
    allowInout(){
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_INOUT');
    },
    // 是否允许导入导出
    allowImportAndExport(){
      return this.allowImport || this.allowExport
    },
    allowImport() {
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_IMPORT') && this.allowCreate
    },
    allowExport() {
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_EXPORT');
    },
    // 是否开放服务商查看服务项目和物料的价格信息
    serviceProviderShowPrice() {
      try {
        const RootWindow = getRootWindow(window);
        const InitData = RootWindow._init ? JSON.parse(RootWindow._init) : {};
        return InitData.serviceProviderShowPrice ?? true;
      } catch (error) {
        return true;
      }
    }
  },
  methods: {
    // 查看产品类型详情
    openProductMenuTab(id) {
      let fromId;
      try {
        fromId = window.frameElement.getAttribute('id');
      } catch (error) {
        
      }
      // this.$platform.openTab({
      //   id: `productV2_catalog_view_${id}`,
      //   title: '产品类型详情',
      //   close: true,
      //   url: `/productV2/catalog/view?id=${id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        fromId
      })
    },
    
    chooseSparepart(value){
      this.model.id = value;
    },
    // 关闭高级搜索弹框
    closeDrawer(){
      this.isExpand = false;
    },
    cancelSelectPart(part) {
      if (!part || !part.id) return;
      this.selected = this.selected.filter(ms => ms.id !== part.id);
      this.toggleSelection([part]);
    },
    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows) {
        for(let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every(item => {
            return item.id !== row.id;
          })
          if(isNotOnCurrentPage) return
        }
        rows.forEach(row => {
          this.$refs.table.toggleRowSelection(row);
        });
      } else {
        this.$refs.table.clearSelection();
        this.selected = [];
      }
    },
    async editBatch() {
      let form = this.$refs.editBatchForm;
      // validate field
      let params = await form.pack();
      if (!params) return;
      params.ids = this.selected.map(part => part.id);
      this.pending = true;

      try {
        let result = await this.$http.post('/partV2/category/batchUpdateField', params);
        if(result.status == 0){
          this.$platform.toast(this.$t('common.base.tip.bulkEditSuccess'));
          this.editBatchDialog = false;
          form.reset();
          // reload data
          this.loadData();
        }else{
          this.$platform.alert(result.message);
        }

      } catch (error) {
        console.log(error)
      }
      this.pending = false;
    },
    openEditSparepartDialog(value) {
      this.trackEventHandler('batchEdit');
      // 编辑的权限
      if (!this.selected.length) {
        return this.$platform.alert(this.$t('part.list.text13'));
      }
      this.editBatchDialog = true;
    },

    chooseColnum(column){
      this.trackEventHandler('selectColumn');

      column.show = !column.show;

      this.saveColumnStatusToStorage()

      // let data = {};
      // this.columns.forEach(item => data[item.field] = item.show);
      // StorageUtil.save(STORAGE_COLNUM_KEY, data);
    },
    chooseDate(range){
      this.dateRange = range;
      const [start, end] = range || []

      this.model.timeStart = start
      this.model.timeEnd = end
    },
    exportPart(exportAll = false){
      /*bugfix: 37489 导出权限只根据"导出"，按钮显示隐藏已经控制了，不需要再加这些*/
    //  if(!this.allowImportAndExport || !this.allowEdit || !this.allowInout) return;

      let ids = [];
      let fileName = this.$t('part.list.text18', {data1: formatDate(safeNewDate(), 'YYYY-MM-DD')});

      if(!exportAll){
        if(this.selected.length == 0) return this.$platform.alert(this.$t('common.base.tip.exportNoChoice'));
        ids = this.selected.map(item => item.id);
      }

      this.$refs.exportPanel.open(ids, fileName);
    },
    importSucc(){
      this.loadData();
    },
    importPart(){ 
      if(!this.allowImportAndExport || !this.allowEdit || !this.allowInout) return;
      let instance = this.$refs.importPart;
      instance.open();
    },
    importEditPart(){ 
      if(!this.allowEdit) return;    
      let param = {
        ids: []
      };

      // if (!this.selected.length) {
      // return this.$platform.alert('您尚未选择数据，请选择数据后点击批量更新');
      // }

      if(this.selected.length > 0) param.ids = this.selected.map(item => item.id);
      param = _.assign(param, this.model);
      delete param.pageSize;
      delete param.pageNum;
      delete param.sortBy;
      let arr = [];
      
      this.editPartPostParam = param;
      for (let i in param) {
        arr.push(`${i }=${ param[i]}`);
      }
      this.editPartParam = arr.join('&');

      let instance = this.$refs.importEditPart;
      instance.open(param);
    },
    create(){
      this.trackEventHandler('create');
      if(!this.allowCreate) return;
      window.location.href = `${this.$resourcePrefix}/partV2/category/create`
    },
    openDetail(row){
      // this.$platform.openTab({
      //   id: `partV2_category_detail_${row.id}`,
      //   url:`/partV2/category/detail?id=${row.id}`,
      //   title: '备件品类详情',
      //   close: true
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePartCategoryDetail,
        key: row.id,
        params: `id=${row.id}`,
      })
    },
    async remove(){
      this.trackEventHandler('remove');
      try {
        let selected = this.selected;

        if(!this.allowEdit) return;
        if(!selected || selected.length == 0) return this.$platform.alert(this.$t('part.list.text14'))
        if(!await this.$platform.confirm(this.$t('part.list.text15'))) return;

        this.pending = true;
        let ids = selected.map(item => item.id);
        let result = await this.$http.post('/partV2/category/batchRemove', ids);
        
        if(result.status == 0){
          this.selected = [];
          this.loadData();
        }else{
          this.$platform.alert(result.message || this.$t('part.list.text16'));
        }

        this.pending = false;
      } catch (error) {
        console.warn(error)
      }
    },
    toggleEnable(row){
      if(!this.allowEdit) return;

      let params = {
        id: row.id,
        enable: row.enable
      }

      row.disabled = true;
      this.$http.post('/partV2/category/toggleEnable', params, false).then(result => {
        if(result.status != 0){
          row.enable = !row.enable;
          this.$platform.alert(result.message);
        }
      })
        .catch(err => console.warn(err))
        .finally(() => {
          row.disabled = false;
        })
    },
    // select part
    handleSelection(selection) {
      let tv = this.computeSelection(selection);
      // 在需要限制最多选择500个备件时，取消function内部全部注释即可
      let original = this.selected
        .filter(ms => this.page.list.some(cs => cs.id === ms.id));
      let unSelected = this.page.list
        .filter(c => original.every(oc => oc.id !== c.id));

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.table.toggleRowSelection(row, false);
            })
            : this.$refs.table.clearSelection();
        })
        return this.$platform.alert(this.$t('common.base.tip.maxDataCanChooseTips', {data1: this.selectedLimit}));
      }
      this.selected = tv;

      this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    computeSelection(selection) {
      let tv = [];
      tv = this.selected
        .filter(ms => this.page.list.every(c => c.id !== ms.id));
      tv = _.uniqWith([...tv, ...selection], _.isEqual);
      return tv;
    },
    matchSelected() {
      if (!this.selected.length) return;
      const selected = this.page.list
        .filter(c => {
          if (this.selected.some(sc => sc.id === c.id)) {
            this.selected = this.selected.filter(sc => sc.id !== c.id);
            this.selected.push(c);
            return c;
          }
        }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    initialize(){
      this.loadData();
    },
    jump(pageNum){
      this.model.pageNum = pageNum;
      this.loadData();
    },
    pageSizeChange(pageSize){
      this.model.pageSize = pageSize;
      this.originModel.pageSize = pageSize;
      
      this.loadData();

      // 存入localStorage
      StorageUtil.save(STORAGE_PAGESIZE_KEY, pageSize);
    },
    search(){
      this.trackEventHandler('search')
      this.isExpand = false;
      this.model.pageNum = 1;
      this.loadData();
    },
    reset(){
      this.isExpand = false;
      this.model = _.assign({}, this.originModel);
      this.dateRange = [];
      this.$refs.table.clearSort();
      this.loadData();
    },
    sort({column, prop, order}){
      let sortBy = {};
      
      if(prop){
        let tableName = 'sparepart';
        let key = `${tableName}.${prop}`
        sortBy[key] = order == 'ascending';
      }

      this.model.sortBy = sortBy;
      this.loadData();
    },
    async loadData(){
      // let loading = this.$loading();
      this.pageLoading = true;
      try{
        this.page = await this.fetchData();
        this.model.pageNum = this.page.pageNum;
        this.model.pageSize = this.page.pageSize;

        this.matchSelected();
      }catch(error){
        console.warn(error)
      }
      // loading.close();
      this.pageLoading = false;
    },
    fetchData(){
      const params = objectDateToTimestamp({...this.model}, [
        'startTime',
        'endTime',
      ]);
      return this.$http.post('/partV2/category/listData', params).then(result => {
        let list = result.list || [];
        list.forEach(item => {
          item.disabled = false;
          item.salePrice = item.salePrice.toFixed(2);
          item.costPrice = item.costPrice.toFixed(2);
        });
        return result;
      })
    },
    buildParams(pageNum, pageSize){
      return {
        ...this.model,
        pageNum,
        pageSize
      };
    },
    buildColumns(){
      let localData = StorageUtil.get(STORAGE_COLNUM_KEY) || {};

      let columns = [
        {
          label: this.$t('common.base.serialNumber'),
          field: 'serialNumber',
          show: true,
          fixed: 'left',
          sortable: 'custom',
          minWidth: 150,
          export: true,
        },
        {
          label: this.$t('common.base.name'),
          field: 'name',
          show: true,
          minWidth: 150,
          export: true,
        },
        {
          label: this.$t('common.form.preview.serviceItem.colum3'),
          field: 'type',
          show: true,
          minWidth: 100,
          export: true,
        },
        {
          label: this.$t('common.form.preview.sparepart.label3'),
          field: 'standard',
          show: true,
          minWidth: 100,
          export: true,
        },
        {
          label: this.$t('common.form.preview.serviceItem.colum4'),
          field: 'unit',
          show: true,
          minWidth: 100,
          export: true,
        },
        {
          label: this.$t('product.component.miniTable.partType.salePrice'),
          field: 'salePrice',
          show: true,
          minWidth: 80,
          export: true,
        },
        {
          label: this.$t('product.component.miniTable.partType.costPrice'),
          field: 'costPrice',
          show: true,
          minWidth: 80,
          export: true,
        },
        {
          label: this.$t('common.base.explain'),
          field: 'description',
          show: true,
          minWidth: 120,
          export: true,
        },
        {
          label: this.$t('common.label.enableOrDisabled'),
          field: 'enable',
          width: 100,
          show: true,
          export: true,
        },
        {
          label: this.$t('common.base.column.createTime'),
          field: 'createTime',
          show: true,
          width: 180,
          sortable: 'custom',
          export: true,
        }
      ]
      
      if(this.openSuperCodePro) {
        // 如果没有开启超级二维码，需要删除关联产品类型
        let proIndex = columns.indexOf(columns.filter(item=>item.field === 'enable')[0])
        let pro = {
          label: this.$t('common.form.type.related_catalog'),
          field: 'productTypeList',
          exportAlias: 'catalogId',
          show: false,
          width: 150,
          exportNoChecked: true,
          export: true,
        }
        if(proIndex != -1) columns.splice(proIndex, 0, pro)
      }
      columns.forEach(column => {
        let isShow = localData[column.field];
        if(typeof isShow == 'boolean') column.show = isShow;
      })
      
      // 是否隐藏销售单价和出库价
      if(!this.serviceProviderShowPrice) {
        columns = columns.filter(column => column.field !== 'salePrice' && column.field !== 'costPrice')
      }

      return columns;
    },
    buildExportColumns() {
      const fixedFields = [{
        label: this.$t('part.list.text17'),
        field: 'id',
        show: true,
      }]

      const buildColumns = this.buildColumns();

      return buildColumns.concat(fixedFields);
    },
    // TalkingData事件埋点
    trackEventHandler (type) {
      switch (type) {
      case 'search':
        this.$tdOnEvent('pc：备件品类-搜索事件');
        break;
      case 'reset':
        this.$tdOnEvent('pc：备件品类-重置事件');
        break;
      case 'advSearch':
        this.$tdOnEvent('pc：备件品类-高级搜索事件');
        break;
      case 'create':
        this.$tdOnEvent('pc：备件品类-新建事件');
        break;
      case 'remove':
        this.$tdOnEvent('pc：备件品类-删除事件');
        break;
      case 'batchEdit':
        this.$tdOnEvent('pc：备件品类-批量编辑事件');
        break;
      case 'selectColumn':
        this.$tdOnEvent('pc：备件品类-选择列事件');
        break;
      case 'moreAction':
        this.$tdOnEvent('pc：备件品类-更多操作事件');
        break;
      default:
        break;
      }
    },
    // 构建表格列
    buildTableColumn() {
      let baseColumns = this.buildColumns();
      const localStorageData = this.getLocalStorageData();
      let columnStatus = (localStorageData.columnStatus && localStorageData.columnStatus[this.selectColumnState]) || [];
      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});
      let columns = [...baseColumns].map(col => {
        let show = col.show;
        let width = col.width;
        let localField = localColumns[col.field];
        if (null != localField) {
          width = typeof localField.width == 'number'
            ? `${localField.width}px`
            : `${localField.width}`.indexOf('px') ? localField.width : '';
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.type = 'column';

        return col;
      });

      if (this.isBasicEditionHideProduct) {
        columns = columns.filter(item => item.field !== 'esProductEntities')
      }

      return columns;
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        // selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 12;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    }
  },
  mounted(){
    let initData = this.initData || {};

    this.types = initData.sparepartType || [];
    this.units = initData.units || [];
    this.auths = initData.auths || {};
    this.productType = initData.productType || [];
    this.openSuperCodePro = initData.openSuperCodePro !== false;
    this.columns = this.buildTableColumn();
    this.exportColumns = this.buildExportColumns();
    this.initialize();
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })
    
  },
  components: {
    [PartEditBatchForm.name]: PartEditBatchForm,
    [PartImport.name]: PartImport,
    BaseSearchDrawer
  }
}
</script>

<style lang="scss">
.capp{
  max-width: 360px;
}
// superscript
.part-name-superscript-td {
  padding: 0 !important;
  & > div {
    height: 43px;
    line-height: 43px !important;
    a {
      display: inline-block;
      height: 43px;
      line-height: 43px;
    }
  }
}

// -------- part selected panel --------
.part-selected-count {
  @include fontColor();
  padding: 0 3px;
  width: 15px;
  text-align: center;
  cursor: pointer;
  font-size: 13px;
}

.part-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);

  .part-selected-tip {
    padding-top: 80px;

    img {
      display: block;
      width: 160px;
      margin: 0 auto;
    }

    p {
      text-align: center;
      color: $text-color-regular;
      margin: 8px 0 0 0;
      line-height: 20px;
    }
  }

  .part-selected-list {
    height: 100%;
    padding: 10px;
    overflow-y: auto;

    .part-selected-row {
      display: flex;
      flex-flow: row nowrap;
      line-height: 36px;
      border-bottom: 1px solid #ebeef5;
      font-size: 13px;

      &:hover {
        background-color: #f5f7fa;

        .part-selected-delete {
          visibility: visible;
        }
      }
    }

    .part-selected-head {
      background-color: #F0F5F5;
      color: #333;
      font-size: 14px;
    }

    .part-selected-sn {
      padding-left: 10px;
      width: 150px;
      @include text-ellipsis;
    }

    .part-selected-name {
      padding-left: 10px;
      flex: 1;
      @include text-ellipsis;
    }

    .part-selected-delete {
      width: 36px;
    }

    .part-selected-row button.part-selected-delete {
      padding: 0;
      width: 36px;
      height: 36px;
      border: none;
      background-color: transparent;
      outline: none;
      color: #646B78;
      visibility: hidden;

      i {
        font-size: 14px;
      }

      &:hover {
        color: #e84040;
      }
    }
  }
}

.part-panel-btn {
  float: right;
  cursor: pointer;
  width: 16px;
  height: 16px;
  background: url("../../../assets/img/clear.png") no-repeat center;
  background-size: cover;

  &:hover {
    background: url("../../../assets/img/clear-hover.png") no-repeat center;
    background-size: cover;
  }
}


</style>

<style lang="scss" scoped>
  .base-search-group-container .base-search {
    justify-content: flex-end;
  }
  .page{
    overflow:visible;
  }
  .table-primary {
    color: $color-primary;
    text-decoration: none;
    cursor: pointer;
  }
</style>
